//
//  NetWorkTool.m
//  ChatForHot
//
//  Created by FLY on 2018/10/9.
//  Copyright © 2018年 FLY. All rights reserved.
//

#import "NetWorkTool.h"
#import "APPINFO.h"
#import "UserInfoModel.h"
#import "NSString+Methods.h"
#import "AFNetworking.h"
#import <CommonCrypto/CommonDigest.h>
#import "MBProgressHUD.h"
#import "EaseSDKHelper.h"
@implementation NetWorkTool

+ (void)HOTCHATRequestWithStringURL: (NSString *) stringURL
                           progress:(void (^)(NSProgress *progress))Progress
                         RequestWay: (NSString *) requestStyle
                              Parma: (NSDictionary *) parma
                       SuccessBlock: (void(^)(BOOL isSucess, NSDictionary * resultDictionary)) SuccessBlock
                       FailureBlock: (void(^)(NSError * error)) FailureBlock{
    
    NSMutableDictionary *mparameters = [NSMutableDictionary dictionaryWithDictionary:parma];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    APPINFO *appInfo = [APPINFO defaultManager];
    [mparameters setValue:appInfo.appid forKey:@"appid"];
    [mparameters setValue:appInfo.ver forKey:@"appVer"];
    [mparameters setValue:appInfo.channelId forKey:@"channel"];

    NSString *timeStr = systemTimes();
    NSString *sign = [timeStr HOTCHATmd5WithKey:@"chichao123"];
    [manager.requestSerializer setValue:timeStr forHTTPHeaderField:@"X-Time"];
    [manager.requestSerializer setValue:sign forHTTPHeaderField:@"X-Sign"];
    [manager.requestSerializer setValue:appInfo.channelId forHTTPHeaderField:@"channel"];
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    if ([requestStyle isEqualToString:@"GET"]){
        
        [manager GET:stringURL parameters:mparameters progress:^(NSProgress * _Nonnull uploadProgress) {
            if (Progress) {
                Progress(uploadProgress);
            }
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            NSError *error;
            NSDictionary *weatherDic = [NSJSONSerialization JSONObjectWithData:responseObject
                                                                       options:NSJSONReadingMutableLeaves
                                                                         error:&error];
            if (weatherDic == nil) {
                NSLog(@"%@",[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
            }
            NSString *code = [weatherDic objectForKey:@"code"];
            [self HOTCHATwillShowMessageWithDic:weatherDic code:code];
            if (SuccessBlock) {
                SuccessBlock([code isEqualToString:@"0"],weatherDic);
            }
//            if (error) {
//                [self loadWithData:responseObject];
//            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            if (FailureBlock) {
                FailureBlock(error);
            }
        }];
    }else{
        //post
        [manager POST:stringURL parameters:mparameters progress:^(NSProgress * _Nonnull uploadProgress) {
            if (Progress) {
                Progress(uploadProgress);
            }
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            NSError *error;
            
            NSDictionary *weatherDic = [NSJSONSerialization JSONObjectWithData:responseObject
                                                                       options:NSJSONReadingMutableContainers
                                                                         error:&error];
            if (weatherDic == nil) {
                NSLog(@"%@",[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
            }
            NSString *code = [weatherDic objectForKey:@"code"];
            [self HOTCHATwillShowMessageWithDic:weatherDic code:code];
            if (SuccessBlock) {
                SuccessBlock([code isEqualToString:@"0"],weatherDic);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            if (FailureBlock) {
                FailureBlock(error);
            }
        }];
    }
}
+ (void)HOTCHATUpdateToken{
    __weak typeof (self) weakself = self;
    APPINFO *appInfo = [APPINFO defaultManager];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setValue:appInfo.token forKey:@"token"];
    //    [ONENIGHTStringUtils getTheinitTokenApi]
    [NetWorkTool HOTCHATRequestWithStringURL:UPDATETOKEN_URL progress:^(NSProgress * _Nonnull progress) {
        
    } RequestWay:@"POST" Parma:dic SuccessBlock:^(BOOL isSucess, NSDictionary * _Nonnull resultDictionary) {
        if ([resultDictionary[@"code"] isEqualToString:@"0"]) {
            UserInfoModel *model = [[UserInfoModel alloc]init];
            [model setValuesForKeysWithDictionary:resultDictionary[@"data"]];
            [model HOTCHATsaveTheUserInfo];
//            [weakself HOTCHATUpdateToken];
            NSLog(@"update token");
        }else{
//            [self ONENIGHTloginAction];
        }
    } FailureBlock:^(NSError * _Nonnull error) {
        
    }];

}

+ (void)HOTCHATUploadImageData:(NSString *)URLString
                    parameters:(NSMutableDictionary *)parameters
                      fileData:(void (^)(id<AFMultipartFormData> _Nonnull))mformData
                      progress:(void (^)(NSProgress * _Nonnull))muploadProgress
                       success:(void (^)(NSURLSessionDataTask * _Nonnull, NSString * _Nonnull, NSDictionary * _Nonnull))msuccess
                       failure:(void (^)(NSURLSessionDataTask * _Nonnull, NSError * _Nonnull))mfailure {
    if (parameters == nil) {
        parameters = [[NSMutableDictionary alloc] init];
    }
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    APPINFO *appInfo = [APPINFO defaultManager];
    [parameters setValue:appInfo.appid forKey:@"appid"];
    [parameters setValue:appInfo.ver forKey:@"appVer"];
    [parameters setValue:appInfo.channelId forKey:@"channel"];
    
    NSString *timeStr = systemTimes();
    NSString *sign = [timeStr HOTCHATmd5WithKey:@"chichao123"];
    [manager.requestSerializer setValue:timeStr forHTTPHeaderField:@"X-Time"];
    [manager.requestSerializer setValue:sign forHTTPHeaderField:@"X-Sign"];
    [manager.requestSerializer setValue:appInfo.channelId forHTTPHeaderField:@"channel"];
    
    [manager POST:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if(mformData){
            mformData(formData);
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        if (muploadProgress) {
            muploadProgress(uploadProgress);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError *error;
        
        NSDictionary *weatherDic = [NSJSONSerialization JSONObjectWithData:responseObject
                                                                   options:NSJSONReadingMutableContainers
                                                                     error:&error];
        if (weatherDic == nil) {
            NSLog(@"%@",[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
        }
        NSString *code = [weatherDic objectForKey:@"code"];
        [self HOTCHATwillShowMessageWithDic:weatherDic code:code];
        if (msuccess) {
            msuccess(task,code,weatherDic);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (mfailure) {
            mfailure(task,error);
        }
    }];
    
}
+ (void)HOTCHATwillShowMessageWithDic:(NSDictionary *)dic code:(NSString *)code{
    
    if ([code isEqualToString:@"1"]) {
        NSString *message = [dic valueForKey:@"message"];
        if (message.length > 0) {
            [self HOTCHATshowMessage:message];
        }
    }
    
    if ([code isEqualToString:@"2001"]) {
        //缺少参数"];
        NSLog(@"miss_pra_%@",NSStringFromSelector(_cmd));
    }else if ([code isEqualToString:@"2002"]) {
        //账号不存在"];
        [self HOTCHATshowMessage:NSLocalizedString(@"msgShow1", nil)];
    }else if ([code isEqualToString:@"2003"]) {
        //帐号已被封号"];
        [self HOTCHATshowMessage:NSLocalizedString(@"msgShow2", nil)];
    }else if ([code isEqualToString:@"3001"]) {
        //网路异常,请稍后再试"];
        [self HOTCHATshowMessage:NSLocalizedString(@"msgShow7", nil)];
    }else if ([code isEqualToString:@"3002"]) {
        //当前设备注册用户已达上限,请明日再注册"];
        [self HOTCHATshowMessage:NSLocalizedString(@"msgShow8", nil)];
    }else if ([code isEqualToString:@"3003"]) {
        //人脸验证失败，请重新验证"];
        [self HOTCHATshowMessage:NSLocalizedString(@"msgShow9", nil)];
    }else if ([code isEqualToString:@"3004"]) {
        //token失效 请重新登录"];
        [self HOTCHATUpdateToken];
    }else if ([code isEqualToString:@"2000"]) {
        //无效的请求"];
        [self HOTCHATshowMessage:NSLocalizedString(@"msgShow15", nil)];
    }else if ([code isEqualToString:@"4011"]) {
        //最多上传20个视频"];
        [self HOTCHATshowMessage:NSLocalizedString(@"msgShow20", nil)];
    }else if ([code isEqualToString:@"4012"]) {
        //上传失败请重试"];
        [self HOTCHATshowMessage:NSLocalizedString(@"msgShow21", nil)];
    }
}
//showmessage
+ (void)HOTCHATshowMessage:(NSString *)message{
    
    UIView *windowview = [[UIApplication sharedApplication].delegate window];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:windowview animated:YES];
    hud.userInteractionEnabled = NO;
    hud.color = [UIColor colorWithWhite:0 alpha:0.7];
    // Configure for text only and offset down
    hud.mode = MBProgressHUDModeText;
    hud.labelText = message;
    hud.margin = 14.f;
    hud.removeFromSuperViewOnHide = YES;
    hud.yOffset = (HOTCHATUIHEIGHT / 2 - 90);
    [hud hide:YES afterDelay:2.3];
}
//im 消息
+ (void)HOTCHATsendMessage:(NSString *)message toUser:(NSString *)userId{
    
    if (message.length == 0) {
        
        return;
    }
    //一些信息
    NSMutableDictionary *ext = [NSMutableDictionary new];
    [ext setValue:HOTCHATAPPINFO.nickName forKey:@"nickName"];
    [ext setValue:HOTCHATAPPINFO.headPic forKey:@"headPic"];
    [ext setValue:HOTCHATAPPINFO.code forKey:@"vip"];
    EMMessage *msg = [EaseSDKHelper getTextMessage:message to:userId messageType:EMChatTypeChat messageExt:ext];
    [[EMClient sharedClient].chatManager sendMessage:msg progress:^(int progress) {
        
    } completion:^(EMMessage *message, EMError *error) {
        if (!error) {
            
            NSLog(@"send message success");
        }
    }];
    
}
//透传消息
+ (void)HOTCHATsendCmdMessageToUser:(NSString *)uid dic:(NSDictionary *)dic{
    
    EMCmdMessageBody *body = [[EMCmdMessageBody alloc] initWithAction:@"guest"];
    NSString *from = [[EMClient sharedClient] currentUsername];
    
    // 生成message
    EMMessage *message = [[EMMessage alloc] initWithConversationID:uid from:from to:uid body:body ext:dic];
    message.chatType = EMChatTypeChat;// 设置为单聊消息
    
    [[EMClient sharedClient].chatManager sendMessage:message progress:^(int progress) {
        
    } completion:^(EMMessage *aMessage, EMError *aError) {
        if (!aError) {
            NSLog(@"success");
        }else{
            NSLog(@"failed");
        }
    }];
}
@end
